﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WineStore.DAL;
using System.Data;
using System.Data.Entity;
using PagedList.Mvc;
using PagedList;
using WineStore.Models;
using CaptchaMvc.HtmlHelpers;
using System.Web.Security;
using System.Net;

namespace WineStore.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Index/

        public ActionResult Index(int? page)
        {


            using (WineDbContext db = new WineDbContext())
            {


                var sims = db.Sims.Include(s => s.Supplier).Include(s => s.CategorySim).OrderByDescending(s => s.SimId).ToList();

                int pageSize = 50;
                int pageNumber = (page ?? 1);

                // Thiet lap thuoc tinh khi phan trang
                PagedListRenderOptions pro = new PagedListRenderOptions();
                pro.MaximumPageNumbersToDisplay = 5;
                pro.LinkToLastPageFormat = "Trang cuối";
                pro.DisplayLinkToLastPage = true;
                pro.LinkToFirstPageFormat = "Trang đầu";
                pro.DisplayLinkToFirstPage = true;
                pro.LinkToNextPageFormat = ">>";
                pro.DisplayLinkToNextPage = true;
                pro.LinkToPreviousPageFormat = "<<";
                pro.DisplayLinkToPreviousPage = true;

                ViewBag.Pro = pro;

                return View(sims.ToPagedList(pageNumber, pageSize));
            }

        }

        //
        // GET: /Order/

        public ActionResult Order(int? id)
        {


            try
            {
                using (WineDbContext db = new WineDbContext())
                {


                    Sim sim = db.Sims.Find(id);
                    ViewBag.Sim = sim;
                    ViewBag.SupplierName = sim.Supplier.SupplierName;
                    ViewBag.CategoryName = sim.CategorySim.CategorySimName;
                }
            }
            catch (DataException)
            {
                ModelState.AddModelError("", "Unable to save changes");
            }
            return View();
        }

        //
        // POST: /Order/

        [HttpPost]
        public ActionResult Order(OrderSim ordersim, int? simId)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    using (WineDbContext db = new WineDbContext())
                    {

                        ordersim.Status = 1;
                        ordersim.OrderDate = DateTime.Now;
                        ordersim.SimId = simId.Value;
                        db.Entry(ordersim).State = EntityState.Added;
                        db.SaveChanges();
                        return RedirectToAction("OrderSuccesses", "Home");
                    }
                }
            }
            catch (DataException)
            {
                ModelState.AddModelError("", "Unable to save changes");
            }
            return View(ordersim);
        }

        //
        // GET: /OrderSuccesses/

        public ViewResult OrderSuccesses()
        {

            return View();
        }

        //
        // GET: /AdvanceSearch/

        public ActionResult AdvanceSearch()
        {

            return View();
        }

        //
        // POST: /ResultAdvanceSearch/

        public ActionResult ResultAdvanceSearch(string currentFilter1, string searchString1, string currentFilter2, string searchString2, string currentFilter3, string searchString3, string currentFilter4, string searchString4, string currentFilter5, string searchString5, int? page)
        {

            if (Request.HttpMethod == "GET")
            {
                searchString1 = currentFilter1;
                searchString2 = currentFilter2;
                searchString3 = currentFilter3;
                searchString4 = currentFilter4;
                searchString5 = currentFilter5;
            }
            else
            {
                page = 1;
            }
            ViewBag.CurrentFilter1 = searchString1;
            ViewBag.CurrentFilter2 = searchString2;
            ViewBag.CurrentFilter3 = searchString3;
            ViewBag.CurrentFilter4 = searchString4;
            ViewBag.CurrentFilter5 = searchString5;



            using (var db = new WineDbContext())
            {
                var sims = db.Sims
                               .Include(s => s.Supplier).Include(c => c.CategorySim);

                if (!String.IsNullOrEmpty(searchString1))
                {
                    sims = sims.Where(s => s.Supplier.SupplierName.ToUpper().Contains(searchString1.ToUpper()));
                }

                if (!String.IsNullOrEmpty(searchString2))
                {
                    sims = sims.Where(s => s.CategorySim.CategorySimName.ToUpper().Contains(searchString2.ToUpper()));
                }

                if (!String.IsNullOrEmpty(searchString3))
                {

                    foreach (var item in sims)
                    {
                        if (Convert.ToInt32(item.SimPrice.Replace(".", "").Replace(" ", "")) < Convert.ToInt32(searchString3.Replace(".", "").Replace(" ", "")))
                        {
                            sims = sims.Where(s => s.SimPrice != item.SimPrice);
                        }
                    }
                }

                if (!String.IsNullOrEmpty(searchString4))
                {

                    foreach (var item in sims)
                    {
                        if (Convert.ToInt32(item.SimPrice.Replace(".", "").Replace(" ", "")) > Convert.ToInt32(searchString4.Replace(".", "").Replace(" ", "")))
                        {
                            sims = sims.Where(s => s.SimPrice != item.SimPrice);
                        }
                    }
                }

                if (!String.IsNullOrEmpty(searchString5))
                {

                    sims = sims.Where(s => s.SimNumber.Replace(".", "").Replace(" ", "").Equals(searchString5.Replace(".", "").Replace(" ", "")));
                }

                sims = sims.OrderByDescending(s => s.SimId);




                int pageSize = 50;
                int pageNumber = (page ?? 1);

                // Thiet lap thuoc tinh khi phan trang
                PagedListRenderOptions pro = new PagedListRenderOptions();
                pro.MaximumPageNumbersToDisplay = 5;
                pro.LinkToLastPageFormat = "Trang cuối";
                pro.DisplayLinkToLastPage = true;
                pro.LinkToFirstPageFormat = "Trang đầu";
                pro.DisplayLinkToFirstPage = true;
                pro.LinkToNextPageFormat = ">>";
                pro.DisplayLinkToNextPage = true;
                pro.LinkToPreviousPageFormat = "<<";
                pro.DisplayLinkToPreviousPage = true;

                ViewBag.Pro = pro;

                return View(sims.ToPagedList(pageNumber, pageSize));
            }
        }

        //
        // POST: /SearchByNumber/

        public ActionResult SearchByNumber(string currentSearchIndex, string SearchIndex, int? page)
        {

            if (Request.HttpMethod == "GET")
            {
                SearchIndex = currentSearchIndex;

            }
            else
            {
                page = 1;
            }
            ViewBag.currentSearchIndex = SearchIndex;

            using (var db = new WineDbContext())
            {
                var sims = db.Sims
                               .Include(s => s.Supplier).Include(c => c.CategorySim);

                if (SearchIndex.StartsWith("*"))
                {

                    sims = sims.Where(s => s.SimNumber.Replace(".", "").Replace(" ", "").Substring(s.SimNumber.Replace(".", "").Replace(" ", "").Length - (SearchIndex.Length - 1), SearchIndex.Length - 1) == SearchIndex.Substring(1, SearchIndex.Length - 1));
                }
                else if (SearchIndex.EndsWith("*"))
                {
                    sims = sims.Where(s => s.SimNumber.Replace(".", "").Replace(" ", "").StartsWith(SearchIndex.Substring(0, SearchIndex.Length - 1)));
                }
                else if (!String.IsNullOrEmpty(SearchIndex))
                {
                    sims = sims.Where(s => s.SimNumber.Replace(".", "").Replace(" ", "").Contains(SearchIndex));
                }

                sims = sims.OrderByDescending(s => s.SimId);

                int pageSize = 50;
                int pageNumber = (page ?? 1);

                // Thiet lap thuoc tinh khi phan trang
                PagedListRenderOptions pro = new PagedListRenderOptions();
                pro.MaximumPageNumbersToDisplay = 5;
                pro.LinkToLastPageFormat = "Trang cuối";
                pro.DisplayLinkToLastPage = true;
                pro.LinkToFirstPageFormat = "Trang đầu";
                pro.DisplayLinkToFirstPage = true;
                pro.LinkToNextPageFormat = ">>";
                pro.DisplayLinkToNextPage = true;
                pro.LinkToPreviousPageFormat = "<<";
                pro.DisplayLinkToPreviousPage = true;

                ViewBag.Pro = pro;

                return View(sims.ToPagedList(pageNumber, pageSize));
            }
        }

        //
        // POST: /SearchByPrice/

        public ActionResult SearchByPrice(string currentFilter1, string searchString1, string currentFilter2, string searchString2, int? page)
        {

            if (Request.HttpMethod == "GET")
            {
                searchString1 = currentFilter1;
                searchString2 = currentFilter2;

            }
            else
            {
                page = 1;
            }
            ViewBag.CurrentFilter1 = searchString1;
            ViewBag.CurrentFilter2 = searchString2;



            using (var db = new WineDbContext())
            {
                var sims = db.Sims
                               .Include(s => s.Supplier).Include(c => c.CategorySim);


                if (!String.IsNullOrEmpty(searchString1))
                {

                    foreach (var item in sims)
                    {
                        if (Convert.ToInt32(item.SimPrice.Replace(".", "").Replace(" ", "")) < Convert.ToInt32(searchString1.Replace(".", "").Replace(" ", "")))
                        {
                            sims = sims.Where(s => s.SimPrice != item.SimPrice);
                        }
                    }
                }

                if (!String.IsNullOrEmpty(searchString2))
                {

                    foreach (var item in sims)
                    {
                        if (Convert.ToInt32(item.SimPrice.Replace(".", "").Replace(" ", "")) > Convert.ToInt32(searchString2.Replace(".", "").Replace(" ", "")))
                        {
                            sims = sims.Where(s => s.SimPrice != item.SimPrice);
                        }
                    }
                }



                sims = sims.OrderByDescending(s => s.SimId);



                int pageSize = 5;
                int pageNumber = (page ?? 1);

                // Thiet lap thuoc tinh khi phan trang
                PagedListRenderOptions pro = new PagedListRenderOptions();
                pro.MaximumPageNumbersToDisplay = 5;
                pro.LinkToLastPageFormat = "Trang cuối";
                pro.DisplayLinkToLastPage = true;
                pro.LinkToFirstPageFormat = "Trang đầu";
                pro.DisplayLinkToFirstPage = true;
                pro.LinkToNextPageFormat = ">>";
                pro.DisplayLinkToNextPage = true;
                pro.LinkToPreviousPageFormat = "<<";
                pro.DisplayLinkToPreviousPage = true;

                ViewBag.Pro = pro;

                return View(sims.ToPagedList(pageNumber, pageSize));
            }
        }


        //
        // POST: /SearchBySupplier/

        public ActionResult SearchBySupplier(int? page, int? supplierId)
        {


            ViewBag.SupplierId = supplierId.Value;
            using (var db = new WineDbContext())
            {


                var sims = db.Sims
                               .Include(s => s.Supplier).Include(c => c.CategorySim)
                               .Where(s => s.SupplierId == supplierId.Value);

                sims = sims.OrderByDescending(s => s.SimId);

                int pageSize = 50;
                int pageNumber = (page ?? 1);

                // Thiet lap thuoc tinh khi phan trang
                PagedListRenderOptions pro = new PagedListRenderOptions();
                pro.MaximumPageNumbersToDisplay = 5;
                pro.LinkToLastPageFormat = "Trang cuối";
                pro.DisplayLinkToLastPage = true;
                pro.LinkToFirstPageFormat = "Trang đầu";
                pro.DisplayLinkToFirstPage = true;
                pro.LinkToNextPageFormat = ">>";
                pro.DisplayLinkToNextPage = true;
                pro.LinkToPreviousPageFormat = "<<";
                pro.DisplayLinkToPreviousPage = true;

                ViewBag.Pro = pro;

                return View(sims.ToPagedList(pageNumber, pageSize));
            }
        }

        //
        // POST: /SearchByCategory/

        public ActionResult SearchByCategory(int? page, int? categoryId)
        {


            ViewBag.CategoryId = categoryId.Value;
            using (var db = new WineDbContext())
            {


                var sims = db.Sims
                               .Include(s => s.Supplier).Include(c => c.CategorySim)
                               .Where(s => s.CategorySimId == categoryId.Value);

                sims = sims.OrderByDescending(s => s.SimId);

                int pageSize = 50;
                int pageNumber = (page ?? 1);

                // Thiet lap thuoc tinh khi phan trang
                PagedListRenderOptions pro = new PagedListRenderOptions();
                pro.MaximumPageNumbersToDisplay = 5;
                pro.LinkToLastPageFormat = "Trang cuối";
                pro.DisplayLinkToLastPage = true;
                pro.LinkToFirstPageFormat = "Trang đầu";
                pro.DisplayLinkToFirstPage = true;
                pro.LinkToNextPageFormat = ">>";
                pro.DisplayLinkToNextPage = true;
                pro.LinkToPreviousPageFormat = "<<";
                pro.DisplayLinkToPreviousPage = true;

                ViewBag.Pro = pro;

                return View(sims.ToPagedList(pageNumber, pageSize));
            }
        }

        //
        // POST: /SearchByFirstNumber/

        public ActionResult SearchByFirstNumber(int? page, string number)
        {


            ViewBag.Number = number;
            using (var db = new WineDbContext())
            {


                var sims = db.Sims
                               .Include(s => s.Supplier).Include(c => c.CategorySim)
                               .Where(s => s.SimNumber.StartsWith(number));

                sims = sims.OrderByDescending(s => s.SimId);

                int pageSize = 50;
                int pageNumber = (page ?? 1);

                // Thiet lap thuoc tinh khi phan trang
                PagedListRenderOptions pro = new PagedListRenderOptions();
                pro.MaximumPageNumbersToDisplay = 5;
                pro.LinkToLastPageFormat = "Trang cuối";
                pro.DisplayLinkToLastPage = true;
                pro.LinkToFirstPageFormat = "Trang đầu";
                pro.DisplayLinkToFirstPage = true;
                pro.LinkToNextPageFormat = ">>";
                pro.DisplayLinkToNextPage = true;
                pro.LinkToPreviousPageFormat = "<<";
                pro.DisplayLinkToPreviousPage = true;

                ViewBag.Pro = pro;

                return View(sims.ToPagedList(pageNumber, pageSize));
            }
        }

        // Autocomplete for textbox search 
        [HttpGet]
        public ActionResult Autocomplete(string term)
        {
            using (var db = new WineDbContext())
            {
                var supplierNames = from s in db.Suppliers
                                    select s.SupplierName;
                string[] items = supplierNames.ToArray();

                var filteredItems = items.Where(
                    item => item.IndexOf(term, StringComparison.InvariantCultureIgnoreCase) >= 0
                    );
                return Json(filteredItems, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpGet]
        public ActionResult AutocompleteCategory(string term)
        {
            using (var db = new WineDbContext())
            {
                var categoryNames = from c in db.CategorySims
                                    select c.CategorySimName;
                string[] items = categoryNames.ToArray();

                var filteredItems = items.Where(
                    item => item.IndexOf(term, StringComparison.InvariantCultureIgnoreCase) >= 0
                    );
                return Json(filteredItems, JsonRequestBehavior.AllowGet);
            }
        }

        //
        // GET: /News/

        public ViewResult News(int? page)
        {


            List<News> news = new List<News>();
            using (WineDbContext db = new WineDbContext())
            {


                news = (List<News>)db.News.OrderByDescending(n => n.NewsId).ToList();

                int pageSize = 5;
                int pageNumber = (page ?? 1);

                // Thiet lap thuoc tinh khi phan trang
                PagedListRenderOptions pro = new PagedListRenderOptions();
                pro.MaximumPageNumbersToDisplay = 5;
                pro.LinkToLastPageFormat = "Trang cuối";
                pro.DisplayLinkToLastPage = true;
                pro.LinkToFirstPageFormat = "Trang đầu";
                pro.DisplayLinkToFirstPage = true;
                pro.LinkToNextPageFormat = ">>";
                pro.DisplayLinkToNextPage = true;
                pro.LinkToPreviousPageFormat = "<<";
                pro.DisplayLinkToPreviousPage = true;

                ViewBag.Pro = pro;

                return View(news.ToPagedList(pageNumber, pageSize));
            }

        }

        public ActionResult NewsDetail(int id)
        {

            ViewBag.News = null;

            using (var db = new WineDbContext())
            {

                ViewBag.News = db.News.Take(5).OrderByDescending(n => n.NewsId).ToList();

                News news = new News();
                news = db.News.Find(id);
                if (news != null)
                {
                    return View(news);
                }
                return RedirectToAction("News", "Home");
            }

        }

        //
        // GET: /ContactUs/

        [HttpGet]
        public ViewResult ContactUs()
        {

            return View();
        }

        //
        // POST: /ContactUs/

        [HttpPost]
        public ActionResult ContactUs(ContactUs contact, string empty)
        {

            try
            {
                if (this.IsCaptchaVerify("Captcha is not valid"))
                {
                    if (ModelState.IsValid)
                    {
                        using (var db = new WineDbContext())
                        {
                            db.Entry(contact).State = EntityState.Added;
                            db.SaveChanges();
                            Setting setting = db.Settings.First();
                            string content = "";
                            //khi khach hang submit thi se gui 1 email thong bao ve mail cua công ty
                            var fromAddress = setting.Email; //day la email cua cong ty se dung de vua gui thong tin vua nhan email
                            string fromPassword = setting.Password;//pass word cua email cong ty

                            string subject = "Phản hồi của khách hàng " + contact.Email;
                            content = "Họ Tên: " + contact.FullName + "\n";
                            content += "Điện Thoại : " + contact.Phone + "\n";
                            if (contact.Email != "")
                            {
                                content += "Email : " + contact.Email + "\n";
                            }
                            content += "Nội dung: " + contact.Comment + "\n";
                            string body = content;
                            var smtp = new System.Net.Mail.SmtpClient();
                            {
                                smtp.Host = "smtp.gmail.com";
                                smtp.Port = 587;
                                smtp.EnableSsl = true;
                                smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                                smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
                                smtp.Timeout = 20000;
                            }
                            smtp.Send(fromAddress, fromAddress, subject, body);
                            return RedirectToAction("Index", "Home");
                        }

                    }
                }
                else
                {
                    Response.Write("<p class='message'>Mã xác nhận không đúng !</p>");
                    return View();
                }
            }
            catch (DataException)
            {
                ModelState.AddModelError("", "Unable to save changes");
            }
            return View(contact);
        }

        //
        // GET: /PHONGTHUY/
        public ViewResult PhongThuy()
        {

            return View();
        }
    }
}
